<div id="header"><p>Register</p></div>
<div>
<?php

if($_GET["action"] === "Register")
{
	if($_POST['user'] === "" || $_POST['pass'] === "") {
		header('Location: ?p=register&action=invalid');
		return;
	}

	$passy = $_POST["pass"];
	$cpassy = $_POST["cpass"];
	if ($passy != $cpassy)
	{
		header('Location: ?p=register&action=badpass');
		return;	
	}

	$stringlength = strlen($passy);
	
	if($stringlength < 6)
	{
		header('Location: ?p=register&action=tooshort');
		return;
	}
	
	// Store username and password into variables
	$user = $_POST["user"];
	$pass = $_POST["pass"];

	// Salt is just the hashed username
	$salt = sha1($user);
	
	// Hashed password is salted
	$codedpass = sha1($pass.$salt);

	// Prepare our createUser call and bind the parameters
	// We do it this way to prevent the hashed password from getting
	// screwed up
	$stmt = $database->prepare("CALL createUser(?,?)");
	$stmt->bind_param('ss',$user,$codedpass);

	// Execute the statement
	$stmt->execute(); 

	// Since the stored procedure doesn't return anything, the only
	// way we can tell if the username is a duplicate is if there is 
	// a database error after attempting to create the user.  The stored
	// procedure must just make an "Insert" call.
	if($database->error)
	{
		header('Location: ?p=register&action=duplicate');
		return;
	}
 
	// On successful registration, redirect to the login form
	header('Location: ?p=loginform&action=registered');
	return;
}

// The following produce error messages depending on the error type
else if($_GET["action"] === "invalid")
{
	echo "<p>Please enter a username and password.</p><br />";
}  
else if ($_GET["action"] === "duplicate")
{
	echo "<p>Username unavailable. Please select a different username</p><br />";
}
else if ($_GET["action"] === "badpass")
{
	echo "<p>Your passwords did not match.</p><br />";
}
else if ($_GET["action"] === "tooshort")
{
	echo "<p>Your password was too short.</p><br />";
}

//
// The following creates the registration form
//
echo '<form name="input" action="?p=register&action=Register" method="post">
			<fieldset>
			<legend>Registration Form</legend>
			<label for="user">Username</label>
			<input size="25" style="font-family:monospace" type="text" name="user" />
			<br/><label for="pass">Password</label><input size="25" style="font-family:monospace" type="password" name="pass" />
			<label for="cpass">Confirm Password</label><input size="25" style="font-family:monospace" type="password" name="cpass" /><br/>
			<br />
			<br/><p>Please make your password at least 6 characters long</p><br />
			<p class="submit"><input type="submit" value="Register" name="submit"></p>
			</fieldset>
			</form>';
?>
</div>
